package controllers

import (
	"strconv"
	"tms-server/env"
	"tms-server/gin/models"

	"strings"

	"tms-server/driver"

	"github.com/gin-gonic/gin"
	"github.com/go-xorm/builder"
)

type RoleControllers struct{}

var RoleContrl = new(RoleControllers)

func (control *RoleControllers) Query(c *gin.Context) (res interface{}, e Error) {
	roles, err := models.FindRoles()
	if err != nil {
		return nil, GenError(err)
	}
	data := make([]map[string]interface{}, 0)
	for _, role := range roles {
		info := map[string]interface{}{
			"id":       role.Role.Id,
			"roleName": role.Role.Name,
			"depId":    role.Dep.Id,
			"depName":  role.Dep.Name,
		}
		data = append(data, info)
	}
	res = data
	return
}

func (*RoleControllers) Get(c *gin.Context) (res interface{}, e Error) {
	name := c.Query("name")
	if name == "" {
		return nil, GenErrorMsg("参数错误")
	}
	role, err := models.FindRole(name)
	if err != nil {
		return nil, GenError(err)
	}
	res = map[string]interface{}{
		"id":       role.Role.Id,
		"roleName": role.Role.Name,
		"depId":    role.Dep.Id,
		"depName":  role.Dep.Name,
	}
	return
}

func (control *RoleControllers) Create(c *gin.Context) (res interface{}, e Error) {
	name := c.PostForm("name")
	depId, _ := strconv.ParseInt(c.PostForm("depId"), 10, 64)
	if name == "" || depId == 0 {
		return nil, GenErrorMsg("参数错误")
	}
	_, err := models.FindDep(depId)
	if err == env.NotFound {
		return nil, GenErrorMsg("岗位不存在")
	} else if err != nil {
		return nil, GenError(err)
	}

	session := driver.X.NewSession()
	defer session.Close()
	session.Begin()
	role := &models.Role{
		Name: name,
	}
	err = role.Create(session)
	if err != nil {
		session.Rollback()
		return nil, GenError(err)
	}
	relRoleDep := models.RelDepRole{
		DepId:  depId,
		RoleId: role.Id,
	}
	err = relRoleDep.Create(session)
	if err != nil {
		session.Rollback()
		return nil, GenError(err)
	}
	session.Commit()
	res = "ok"
	return
}

func (control *RoleControllers) SetAuth(c *gin.Context) (res interface{}, e Error) {
	roleId, _ := strconv.ParseInt(c.PostForm("depId"), 10, 64)
	if roleId == 0 {
		return nil, GenErrorMsg("参数错误")
	}
	authIdsStr := c.PostForm("authIds")
	authIdsSlice := strings.Split(authIdsStr, "_")
	rels := make([]interface{}, 0)
	for _, authStr := range authIdsSlice {
		id, _ := strconv.ParseInt(authStr, 10, 64)
		if id > 0 {
			rel := &models.RelRoleAuthority{
				RoleId:      roleId,
				AuthorityId: id,
			}
			rels = append(rels, rel)
		}
	}
	if len(rels) <= 0 {
		return nil, GenErrorMsg("参数错误")
	}
	session := driver.X.NewSession()
	defer session.Close()
	session.Begin()
	_, err := session.Where(builder.Eq{"role_id": roleId}).Delete(new(models.RelRoleAuthority))
	if err != nil {
		session.Rollback()
		return nil, GenError(err)
	}
	_, err = driver.X.Insert(rels...)
	if err != nil {
		session.Rollback()
		return nil, GenError(err)
	}
	err = session.Commit()
	if err != nil {
		return nil, GenError(err)
	}
	res = "ok"
	return
}

func (control *RoleControllers) Update(c *gin.Context) (res interface{}, e Error) {
	name := c.PostForm("name")
	id, _ := strconv.ParseInt(c.PostForm("id"), 10, 64)
	depId, _ := strconv.ParseInt(c.PostForm("depId"), 10, 64)
	if name == "" || depId == 0 || id == 0 {
		return nil, GenErrorMsg("参数错误")
	}
	session := driver.X.NewSession()
	defer session.Close()
	session.Begin()
	if name != "" {
		rel := &models.Role{
			Id:   id,
			Name: name,
		}
		err := rel.Update(session)
		if err != nil {
			session.Rollback()
			return nil, GenError(err)
		}
	}
	if depId != 0 {
		_, err := driver.X.Where(builder.Eq{"role_id": id}).Delete(new(models.RelDepRole))
		if err != nil {
			session.Rollback()
			return nil, GenError(err)
		}
		relRoleDep := models.RelDepRole{
			DepId:  depId,
			RoleId: id,
		}
		err = relRoleDep.Create(session)
		if err != nil {
			session.Rollback()
			return nil, GenError(err)
		}
	}
	err := session.Commit()
	if err != nil {
		return nil, GenError(err)
	}
	res = "ok"
	return
}

func (control *RoleControllers) Delete(c *gin.Context) (res interface{}, e Error) {
	id, _ := strconv.ParseInt(c.Query("id"), 10, 64)
	if id <= 0 {
		return nil, GenErrorMsg("参数错误")
	}
	session := driver.X.NewSession()
	defer session.Close()
	session.Begin()
	role := &models.Role{
		Id: id,
	}
	err := role.Del(session)
	if err != nil {
		session.Rollback()
		return nil, GenError(err)
	}
	_, err = driver.X.Where(builder.Eq{"role_id": id}).Delete(new(models.RelDepRole))
	if err != nil {
		session.Rollback()
		return nil, GenError(err)
	}
	err = session.Commit()
	if err != nil {
		return nil, GenError(err)
	}
	res = "ok"
	return
}

func (control *RoleControllers) check(module, page string) (e Error) {
	if module == "" || page == "" {
		return GenErrorMsg("参数错误")
	}
	pages, found := env.Authes[module]
	if !found || len(pages) == 0 {
		return GenErrorMsg("模块未找到")
	}
	found = false
	for _, p := range pages {
		if p == page {
			found = true
		}
	}
	if !found {
		return GenErrorMsg("页面未找到")
	}
	return
}
